package eu.connect.jmswrapper;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.jms.*;

public class ConnectJMSReceiver extends Thread {
	
	private Class<?> interfaceClass;
	private Object target;
	private TopicSession tSession;
	private Topic topic;
	private TopicPublisher publisher;
	private ConnectJMSInvokeMessage invokeMsg;
	private String msgID;
	
	public ConnectJMSReceiver(TopicSession tSession, Topic topic, Class<?> interfaceClass, Object target, Message message) throws JMSException {
		this.tSession = tSession;
		this.topic = topic;
		this.interfaceClass = interfaceClass;
		this.target = target;
		this.publisher = this.tSession.createPublisher(this.topic);
		ObjectMessage objMsg = (ObjectMessage) message;
		this.invokeMsg = (ConnectJMSInvokeMessage)objMsg.getObject();
		this.msgID = message.getJMSMessageID();
	}
	
	public void run() {
		Method method;
		ConnectJMSReturnMessage returnMsg = null;
		try {
			method = this.interfaceClass.getMethod(invokeMsg.getMethodName(), invokeMsg.getParameterTypes());
			Object returnObj = method.invoke(this.target, (Object[])invokeMsg.getParameters());
			returnMsg = new ConnectJMSReturnMessage();
			returnMsg.setIsException(false);
			returnMsg.setReturnObj((Serializable)returnObj);
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			returnMsg = new ConnectJMSReturnMessage();
			returnMsg.setIsException(true);
			returnMsg.setReturnObj(e.getTargetException());
		}
		
		ObjectMessage objMsg;
		try {
			objMsg = tSession.createObjectMessage();
			objMsg.setObject(returnMsg);
			objMsg.setJMSCorrelationID(this.msgID);
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			this.publisher.publish(objMsg);
			
		} catch (JMSException e1) {
			e1.printStackTrace();
		}
	}

}
